$(function () {
    layui.use(['form','upload'],function () {
        var form = layui.form;

        var fields,
            attachmentData = [];

        //绑定时间函数
        function bindTime(){
            $(".request_delivery").datetimepicker({
                language: "zh-CN",
                format: "yyyy-mm-dd",
                minView: "month",
                todayHighlight: true,
                autoclose: true,
                todayBtn: true
            });
        }

        //循环遍历序号
        function Traversing() {
            $('.table-detail tbody tr').each(function (n) {
                n = n + 1;
                $(this).children(':first').text(n);
            });
        }

        //要求交期
        bindTime();

        var index = 2;//计数
        //增加产品明细
        $(".table-detail").on('click', '.add-detail-item', function () {

            var html = `
            <tr>
                                <td class="ti-10">1</td>
                                <td>
                                    <input type="text" name="details[${index}][product]" class="layui-input" lay-verify="required" >
                                </td>
                                <td class="ti-10">
                                    <input type="hidden" name="details[${index}][manager_name]" class="layui-input" lay-verify="required" value="产品经理的id"> <!--  选择产品后赋值给此value  -->
                                      <!--  选择产品后将产品经理的名字赋值给此td  -->
                                </td>
                                <td>
                                    <input type="text" name="details[${index}][count]" class="layui-input" lay-verify="required">
                                </td>
                                <td>
                                    <input type="text" name="details[${index}][customer]" class="layui-input" lay-verify="required">
                                </td>
                                <td>
                                    <select name="details[${index}][brand]" lay-search>
                                        <option value=""></option>
                                        ${vendor_brands}
                                    </select>
                                </td>
                                <td>
                                    <input type="text" name="details[${index}][model]" class="layui-input">
                                </td>
                                <td>
                                    <input name="details[${index}][remark]" class="layui-input">
                                </td>
                                <td>
                                    <input type="text" name="details[${index}][request_delivery]" class="layui-input request_delivery" lay-verify="required">
                                </td>
                                <td class="ti-10">
                                    <button type="button" class="layui-btn layui-btn-sm add-detail-item">
                                        <span class="icon-plus"></span>
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger cut-detail-item">
                                        <span class="icon-minus"></span>
                                    </button>
                                </td>
                            </tr>`;

            //追加到当前点击DOM的后面
            $(this).parents('tr').after(html);

            //产品计数加1
            index++;

            //重新绑定时间
            bindTime();

            //循环遍历序号
            Traversing();

            form.render();
        });

        //删除该产品
        $('.table-detail').on('click', '.cut-detail-item', function () {
            // 获取明细数量
            var tr_len = $(this).parents('tbody').find('tr').length;

            //至少保留一项产品
            if (tr_len < 2) {
                layer.msg('至少保留一项明细', {
                    icon: 0,
                    time: 2000
                });
            } else {
                //删掉该产品项
                $(this).parents('tr').remove();

                //循环遍历序号
                Traversing();
            }
        });

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: '/Sample/fileUpload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,xlsx,docx,pdf'
            },
            method: 'POST',
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' +
                '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' +
                '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' +
                '<div class="clearfix"></div>' +
                '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {
            var loading = layer.load(2, {
                shade: [0.5, '#fff']    // 0.5 透明度的白色背景
            });
        });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, {icon: 2, time: 2000});
        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {	//文件了上传成功后触发
            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                var attachmentObject = new Object();
                attachmentObject.savename = response.name;  // 由于后期变动，文件统一重命名，这里将原先的 savename 改为 name
                attachmentObject.ext = response.ext;
                attachmentObject.path = response.path;
                attachmentData.push(attachmentObject);
            } else {
                layer.closeAll();
                layer.msg(response.msg, {icon: 2, time: 2000});
            }
        });

        // 所有文件上传结束时
        uploader.on('uploadFinished', function () {
            // 当文件上传完毕后将数据添加至 formdata 再一并提交
            fields.attachments = attachmentData;
            submitSample().then(function (response) {
                if (response.errno) {
                    layer.closeAll();
                    layer.alert(response.message);
                } else {
                    location.href = '/sample/overview/id/' + response.data.id;
                }
            });
        });

        // 删除队列文件
        $('.uploader-file-queue').on('click', '.icon-remove', function () {
            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            uploader.removeFile(uploader.getFile(id, true));
            // 删除dom节点
            $(this).parent().parent().remove();
        });


        //样品订单保存
        form.on("submit(save)",function (data) {
            fields = data.field;
            // 检查队列是否存在待上传的文件，如果存在则先上传
            if (uploader.getFiles().length) {
                uploader.upload();
            } else {
                /*var loading = layer.load(2, {
                    shade: [0.5, '#fff']    // 0.5 透明度的白色背景
                });*/
                submitSample().then(function (response) {
                    if (response.errno) {
                        layer.close(loading);
                        layer.alert(response.message);
                    } else {
                        location.href = '/sample/overview/id/' + response.data.id;
                    }
                });
            }
        });

        //提交
        function submitSample()
        {
            return new Promise(function (resolve, reject) {
                delete fields.file; // 移除 uploader 携带的 file 属性
                $.post('/Posts/post', fields, function (response) {
                    resolve(response);
                }, 'json');
            });
        }

    })
});